package se.thoka.twt.client.form;

import se.thoka.twt.client.utils.validation.Validation;



public class TWTTypeForm<T> extends TWTForm {

	private final TWTFieldInfo<T>[] fieldInfos;
	
	public TWTTypeForm(TWTFieldInfo<T>[] fieldInfos, boolean defaultValidations) {
		if (fieldInfos == null || fieldInfos.length == 0) {
			throw new IllegalArgumentException("Field infos must not be null or empty.");
		}
		
		this.fieldInfos = fieldInfos;

		for (TWTFieldInfo<T> fieldInfo : fieldInfos) {
			TWTFormField<?> field = fieldInfo.createField();
			if (defaultValidations) {
				for (Validation validation : fieldInfo.createValidations()) {
					field.addValidation(validation);
				}
			}
			add(field);
		}
	}
	
	public TWTFieldInfo<T>[] getFieldInfos() {
		return fieldInfos;
	}
	
	public void populateForm(T type) {
		if (type != null) {
			for (TWTFieldInfo<T> fieldInfo : fieldInfos) {
				getField(fieldInfo).setText(fieldInfo.getValue(type));
			}
		} else {
			reset();
		}
	}
	
	public T populateType(T type) {
		for (TWTFieldInfo<T> fieldInfo : fieldInfos) {
			fieldInfo.setValue(type, getField(fieldInfo).getText());
		}
		
		return type;
	}
}
